<template>
  <div class="meter-report-container">
    <!-- 日期选择和导出区域 -->
    <div class="meter-report-header">
      <CustomDatePicker border :isRange="false" v-model="date" />
      <el-button style="margin-left: auto" type="success" :loading="isExporting" @click="handleExport">
        <template #icon>
          <i class="fa fa-download"></i>
        </template>
        导出
      </el-button>
    </div>

    <!-- 表格区域 -->
    <vxe-table ref="tableRef" height="92%" v-loading="isLoading" border align="center" :data="meterTableData"
      :tree-config="treeConfig" :export-config="exportConfig">
      <!-- 固定列 -->
      <vxe-column fixed="left" type="seq" />
      <vxe-column tree-node fixed="left" field="meter_code" title="编号" />
      <vxe-column fixed="left" field="id" title="表号" />
      <vxe-column field="specification" title="规格" />
      <vxe-column field="yesterday_reading" title="上次读数"></vxe-column>
      <vxe-column field="current_reading" title="本次读数"></vxe-column>
      <vxe-column field="current_reading_time" title="时间">
        <template #default="{ row }">
          {{ dayjs(row.current_reading_time).format("YYYY/MM/DD HH:mm:ss") }}
        </template>
      </vxe-column>
      <vxe-column fixed="right" field="Value" title="用量">
        <template #default="{ row }">
          {{ formatFlowValue(row.Value) }}
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, reactive } from "vue";
import dayjs from "dayjs";
import CustomDatePicker from "@/components/header/CustomDatePicker.vue";
import { useMeterStore } from "@/stores/meter";
import { formatFlowValue, mapMeterData } from "@/utils/meterUtils";
import { getMeterReportApi } from "@/api/meter";

// 状态管理
const meterStore = useMeterStore();
// 组件引用
const tableRef = ref(null);

// 响应式数据
const date = ref(dayjs().subtract(1, "day"));

const dateRange = computed(() => {
  const start = dayjs(date.value).startOf("day").valueOf();
  const end = dayjs(date.value).add(1, "day").startOf("day").valueOf();
  return [start, end];
});

const exportConfig = {
  type: "xlsx",
  includeFooter: true,
  useStyle: true,
  isFooter: true,
  isColgroup: true,
  isAllExpand: true,
  // 分组表头
  filename: "气表日抄表记录",
  sheetName: "表计报表",
  modes: ["current"],
};

const meterTableData = ref([]);

const isLoading = ref(false);
const isExporting = ref(false);

// 树形配置
const treeConfig = reactive({
  transform: true,
  rowField: "id",
  parentField: "parent_id",
  lazy: true,
  hasChild: "hasChild",
  showLine: true,
  loadMethod: ({ row }) => loadChildNodes(row),
});

async function fetchMeterDetail() {
  if (isLoading.value) return;

  try {
    meterTableData.value = [];
    isLoading.value = true;

    let results = await fetchAndProcessMeterData(meterStore.treeDataForChart);

    meterTableData.value = results.filter(Boolean);
    const table = tableRef.value;
  } catch (error) {
    ElNotification({
      type: "error",
      title: "Error",
      message: error.message || "获取气表数据失败",
    });
    console.error("Failed to fetch meter report:", error);
  } finally {
    isLoading.value = false;
  }
}

async function fetchAndProcessMeterData(meters) {
  try {
    let res = await Promise.all(meters.map(async item => {
      return new Promise((resolve) => {
        getMeterReportApi({
          id: item.id,
          start_time: dateRange.value[0],
          end_time: dateRange.value[1]
        }).then((res) => {
          let data = res.aggregated_data[0]
          let localMeterData = {
            ...item, hasChild: Array.isArray(item.children) && item.children.length > 0,
            customChildren: item.children, current_reading: data.end, Value: data.Value, yesterday_reading: data.begin, current_reading_time: data.start_time
          }
          resolve(localMeterData)
        })
      })
    }))
    return res
  } catch (error) {
    handleError(error, "获取电表数据失败")
    return [];
  }
}
async function loadChildNodes(parentNode) {
  try {
    const children = await fetchAndProcessMeterData(parentNode.customChild);
    const validChildren = children.filter(Boolean);
    return validChildren;
  } catch (error) {
    ElNotification({
      type: "error",
      title: "Error",
      message: error.message || "获取气表数据失败",
    });
    console.error("Failed to load child nodes:", error);
    return [];
  }
}

async function handleExport() {
  try {
    isExporting.value = true;
    const table = tableRef.value;

    // 展开所有节点
    for (let i = 0; i < meterStore.meterLevels.length; i++) {
      await table?.setAllTreeExpand(true);
    }
    // 设置导出选项
    await table?.openExport({
      includeFooter: true,
    });
  } finally {
    isExporting.value = false;
  }
}

// 监听数据变化
watch(
  [() => dateRange.value, () => meterStore.treeDataForChart],
  () => {
    fetchMeterDetail();
  },
  { deep: true }
);

// 生命周期钩子
onMounted(async () => {
  if (
    !meterStore.treeDataForChart.length ||
    meterStore.currentSelectedType !== 3
  ) {
    meterStore.setCurrentSelectedType(3);
    await meterStore.fetchMeterList();
  }
  fetchMeterDetail();
});
</script>
<style scoped>
.meter-report-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.meter-report-header {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.meter-report-body {
  flex: 1;
}
</style>
